package com.zzzmh.jfx.controller;

import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;

public class Controller {

    /**
     * 保存表单配置数据
     */
    public void saveFormConfigData(String stringData) {

        System.out.printf("44");
        System.out.print(stringData);
    }

    public void preview(String stringData) {
        System.out.printf("77");
        System.out.print(stringData);
        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();

        Controller controller = new Controller();
        // 注入方法
        engine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState, Worker.State newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        // 获取JS的window对象
                        JSObject window = (JSObject) engine.executeScript("window");
                        // 讲controller注入到window对象中
                        window.setMember("dataExchange", controller);
                        engine.executeScript("window.initFormConfig('" + stringData + "')");
//                        String formData = "{\"name\":\"张三\",\"age\":9}";
//                        engine.executeScript("window.initFormData('" + formData + "')");
                    }
                });

        engine.load(Controller.class.getResource(
                "/web/preview.html").toExternalForm());



        Scene scene = new Scene(webView, 1000, 600);
        Stage stage = new Stage();
        stage.setTitle("预览页面");
        stage.setScene(scene);
        stage.show();
    }

    public void handleFormSubmit(String stringData){
        System.out.printf("66");
        System.out.print(stringData);
    }

    /**
     * 获取后端数据
     */
    public String getData() {
        // 这里假装去数据库查询了一套json数据
        return "{\"name\":\"张三\",\"age\":9}";
    }

    /**
     * 新开一个窗口
     */
    public void open() {
        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();
        engine.load(Controller.class.getResource(
                "/com/zzzmh/jfx/html/new.html").toExternalForm());

        Scene scene = new Scene(webView, 400, 280);
        Stage stage = new Stage();
        stage.setTitle("新开页面");
        stage.setScene(scene);
        stage.show();
    }

    /**
     * 彻底退出程序
     */
    public void exit(){
        Platform.exit();
    }
}